package com.elbis.business.manager;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import com.elbis.business.entity.Gamer;
import com.elbis.business.entity.PendingActivation;
import com.elbis.util.HibernateUtil;

public class ActivationManager implements EntityManager<PendingActivation> {

	private static final Logger logger = Logger
			.getLogger(ActivationManager.class);

	public PendingActivation getForUser(Gamer user) {
		Session session = HibernateUtil.getSession();
		PendingActivation pending = null;
		try {
			pending = (PendingActivation) session
					.createCriteria(PendingActivation.class)
					.add(Restrictions.and(Restrictions.eq("gamer", user)))
					.uniqueResult();
		} catch (HibernateException e) {
			logger.error(e.getMessage());
		} finally {
			session.close();
		}
		return pending;
	}

	@Override
	public void delete(PendingActivation act) {
		Session session = HibernateUtil.getSession();
		Transaction trx = null;
		try {
			trx = session.beginTransaction();
			session.delete(act);
			trx.commit();
		} catch (HibernateException e) {
			if (trx != null) {
				trx.rollback();
			}
			logger.error(e.getMessage());
		} finally {
			session.close();
		}
	}

	@Override
	public void update(PendingActivation act) {
		Session session = HibernateUtil.getSession();
		Transaction trx = null;
		try {
			trx = session.beginTransaction();
			session.update(act);
			trx.commit();
		} catch (HibernateException e) {
			if (trx != null) {
				trx.rollback();
			}
			logger.error(e.getMessage());
		} finally {
			session.close();
		}
	}

	@Override
	public Long save(PendingActivation act) {
		Session session = HibernateUtil.getSession();
		Transaction trx = null;
		Long id = null;
		try {
			trx = session.beginTransaction();
			id = (Long) session.save(act);
			trx.commit();
		} catch (HibernateException e) {
			if (trx != null) {
				trx.rollback();
			}
			logger.error(e.getMessage());
		} finally {
			session.close();
		}
		return id;
	}

}
